package it.disim.tlp.webreputation.business.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;

import it.disim.tlp.webreputation.business.AbstractDataAggregatorFactory;
import it.disim.tlp.webreputation.business.FactoryBuilder;
import it.disim.tlp.webreputation.business.TopicService;
import it.disim.tlp.webreputation.business.UtenteService;
import it.disim.tlp.webreputation.business.model.Connector;
import it.disim.tlp.webreputation.business.model.Sorgente;
import it.disim.tlp.webreputation.business.model.Topic;
import it.disim.tlp.webreputation.business.model.Utente;

public class JDBCTopicService implements TopicService {
	
	/**
	 * The method saves a new topic in the database.
	 * @param topic An object of type Topic () "filled" with all the data to be saved in the DB.
	 * @return int Returns an integer: the ID of the newly inserted row in DB if all went well,
	 * -1 If you have not entered anything.
	 */
	@Override
	public int saveTopic(Topic topic) {
		
		Connection con = DBConnect.getConnection();		
		
		int result = -1;
		
		if(!this.checkIfExist(topic)){					
			
			PreparedStatement st_topic = null;
			try {
				st_topic = con.prepareStatement("INSERT INTO topics (Topic) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
			
				st_topic.setString(1, topic.getTopic());					
				st_topic.executeUpdate();				
				
				//We take the key you just generated by the insertion
				ResultSet keys = st_topic.getGeneratedKeys();  				  
				keys.next();  
				result = keys.getInt(1);  
				keys.close(); 						
			
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return result;
	}

	/**
	 * The method checks if the topic input is already in the database or not. The system checks the string of type String.
	 * Then it checks whether the column "topic" there exists exactly the string of the topic that we have in the object topic in the input.
	 * @param topic An object of type Topic () "filled" with all the data that may need to be saved to DB.
	 * @return boolean Returns a Boolean TRUE if the topic exists in the DB, FALSE if the topic does not exist yet.
	 * -1 If you have not entered anything. 
	 */
	@Override
	public boolean checkIfExist(Topic topic) {
		
		Connection con = DBConnect.getConnection();				
						
		Statement st = null;
		ResultSet rs = null;		
		try {
			st = con.createStatement();			

			rs = st.executeQuery("SELECT * FROM topics WHERE Topic = '" + topic.getTopic() + "'");
			if (rs.next()) {				
				
				return true;
			}
			

		} catch (SQLException e) {
			e.printStackTrace();			
		} finally {
			if (st!=null) {
				try {st.close();} catch (SQLException e) {}
			}

		}
		return false;
		
	}

	

}
